/**
 * Created by Core on 2017/7/22 0022.
 */

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class DownloadManager {
    private String downloadUrl;

    public DownloadManager(String downloadUrl) {
        this.downloadUrl = downloadUrl;
    }

    public static String getFileName(String url) {
        String name = "Null.未解析";
        int index = url.lastIndexOf("/");
        if (index > 0) {
            name = url.substring(index + 1);
            if (name.trim().length() > 0)
                return name;
        }
        return name;
    }

    public void startDownload() {
        try {
        //创建下载的url和保存文件
            URL url = new URL(downloadUrl);
            URLConnection connection = url.openConnection();
            int contentLength = connection.getContentLength();
            System.out.println("Download content length is: " + contentLength);
            String filename = DownloadManager.getFileName(downloadUrl);
            File file = new File(filename);
            System.out.println("file path is: " + file.getAbsolutePath());

        //分割下载任务，启动下载线程
            long sublen = contentLength / 3;
            for (int i = 0; i < 3; i++) {
                long starPos = sublen * i;
                long endPos = sublen * (i + 1) - 1;
                DownloadThread thread = new DownloadThread(starPos, endPos, file, url);
                thread.start();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}